import 'package:pacsun/model/taskDetailModel.dart';
import 'package:pacsun/model/taskModel.dart';
import 'package:pacsun/services/taskService.dart';
import 'package:pacsun/services/uploadService.dart';
import 'package:pacsun/utils/utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:logger/logger.dart';
import 'package:photo_manager/photo_manager.dart';

var logger = Logger();

class TaskDetailProv with ChangeNotifier {
  ContentBo? _ContentBo;

  ReportData? _ReportData;

  List<MediaBoList>? _MediaBoList;

  final TaskDetailModel _taskDetailModel = TaskDetailModel(
    taskDtail: TaskModal.fromJson({}, ''),
    taskType: '',
    contentUrl: '',
    productList: [],
    referenceImages: [],
    taskFlows: [],
    auditUploadPhotos: [],
    enable: false,
    aid: '',
  );
  // 回传链接 input controller
  final TextEditingController _controller = TextEditingController();
  TaskModal? get taskDtail => _taskDetailModel.taskDtail;
  String? get taskType => _taskDetailModel.taskType;
  List<ProductModel>? get productList => _taskDetailModel.productList;

  // 示例图片
  List<String>? get referenceImages =>
      _MediaBoList?.where((e) => e.mediaType == 1) // 先筛选
          .map((e) => e.url) // 取出 url 字段
          .toList();
  // 示例视频
  List<MediaBoList>? get referenceVideos =>
      _MediaBoList?.where((e) => e.mediaType == 2) // 先筛选
          .toList();
  List<FlowItem>? get taskFlows =>
      _taskDetailModel.taskDtail?.frontEndStatus.toArray() ?? [];

  // 审核上传的图片
  List<UploadModel> get auditUploadPhotos =>
      List.unmodifiable(_taskDetailModel.auditUploadPhotos);

  // 发布的帖子
  ContentBo? get contentBo => _ContentBo;

  // 保存按钮状体
  bool get enable =>
      auditUploadPhotos.isNotEmpty && _taskDetailModel.contentUrl.isNotEmpty;

  // 奖励List
  List<AuditLog>? get auditLogList =>
      _taskDetailModel.taskDtail?.taskAuditLogList;

  TextEditingController get inputController => _controller;

  // 截图审核日志
  ReportData? get reportData => _ReportData;

  // 示例资源
  List<MediaBoList> get mediaBoList => _MediaBoList ?? [];

  // 判断是否可以发布
  bool get isJoinNow {
    // 任务是否开始
    if (taskDtail != null) {
      if (diffDateStartNow(taskDtail?.startDate.toInt() ?? 0)) {
        if (_taskDetailModel.taskType == 'ACTIVE') {
          return true;
        }
        if (contentBo != null) {
          if (contentBo?.status == 'DRAFT') {
            return true;
          }
        }
      } else {
        return false;
      }
    }

    return false;
  }

  // 判断是否过期
  bool get isExpired {
    String diffTimeStr = formatUSTimeDiff(taskDtail?.endDate ?? 0);
    return diffTimeStr.contains('-');
  }

  void initTaskDetail(String id) async {
    Map<String, dynamic>? result;
    print('${id}-----${taskType}');
    if (taskType == 'My Tasks') {
      result = await TaskApi().getMyTaskDetail(id.toString());
    }
    if (taskType == 'ACTIVE') {
      result = await TaskApi().getTaskDetail(id.toString());
    }
    _taskDetailModel.taskDtail =
        TaskModal.fromJson(result?['data'] ?? {}, taskType ?? '');
    if (result?['data']?['latestContentBo'] != null) {
      _ContentBo = ContentBo.fromJson(result?['data']?['latestContentBo']);
    }
    if (result?['data']?['taskReportDataBoList'] != null) {
      _ReportData =
          ReportData.fromMap(result?['data']?['taskReportDataBoList'][0]);
    }
    if (taskDtail?.taskConfigMediaBoList != null) {
      _MediaBoList = (taskDtail?.taskConfigMediaBoList
              .map((e) => MediaBoList.fromMap(e))
              .toList()) ??
          [];
    }
    setProductList();
    setReferenceImages();
    notifyListeners();
  }

  void setProductList() {
    final rawList =
        _taskDetailModel.taskDtail?.taskConfig['productBoList'] as List? ?? [];
    _taskDetailModel.productList = rawList
        .map((e) => ProductModel.fromJson(e as Map<String, dynamic>))
        .toList();
  }

  void setReferenceImages() {
    final rawList =
        _taskDetailModel.taskDtail?.taskConfig['images'] as List? ?? [];
    _taskDetailModel.referenceImages = rawList.map((e) => e as String).toList();
  }

  void clearTaskDetail() {
    _taskDetailModel.taskDtail = null;
    _taskDetailModel.productList = [];
    _taskDetailModel.referenceImages = [];
    _taskDetailModel.contentUrl = '';
    _taskDetailModel.auditUploadPhotos = [];
    _taskDetailModel.taskType = '';
    _controller.text = '';
    _ContentBo = null;
    _MediaBoList = [];
    if (inputController.hasListeners) {
      inputController.dispose();
    }

    // notifyListeners();
  }

  void setTaskType(String taskType) {
    _taskDetailModel.taskType = taskType;
  }

  // 设置选中的图片
  void setauditUploadPhotos(List<AssetEntity> photos) async {
    print(photos);
    _taskDetailModel.auditUploadPhotos = photos.map((e) {
      return UploadModel.fromJson({
        "startUpload": false,
        "endUpload": false,
        "errorUpload": false,
        "successUpload": false,
        "assetEntity": e,
        "progress": 0,
      });
    }).toList();

    notifyListeners();
  }

  // 删除某个图片
  void removePhotos(AssetEntity file, int index) {
    // List<UploadModel> newFiles = _taskDetailModel.auditUploadPhotos
    //     .where((e) => e.assetEntity.id != file.id)
    //     .toList();

    // _taskDetailModel.auditUploadPhotos = newFiles;
    _taskDetailModel.auditUploadPhotos.removeAt(index);
    notifyListeners();
    print('111');
  }

  void setContentUrl(String value) {
    _taskDetailModel.contentUrl = value;
    notifyListeners();
  }

  // 上传图片
  Future<bool> saveAndUpload() async {
    // List<Future> uploadFutures = auditUploadPhotos.map((file) {
    //   file.startUpload = true;
    //   return UploadService().uploadImage(
    //     file.assetEntity,
    //     onSendProgress: (int count, int total) {
    //       file.progress = ((count / total) * 100).floor();
    //       if (file.progress == 100) {
    //         file.endUpload = true;
    //       }
    //       notifyListeners();
    //     },
    //   );
    // }).toList();

    try {
      // List<dynamic> content = await Future.wait(uploadFutures);
      notifyListeners();
      List<String> content = await UploadService()
          .uploadImages(auditUploadPhotos.map((e) => e.assetEntity).toList());
      await TaskApi().taskSaveUpload({
        'content': content,
        'taskRecordId': _taskDetailModel.taskDtail?.id,
        'contentUrl': _taskDetailModel.contentUrl
      });
      inputController.text = '';
      initTaskDetail(_taskDetailModel.taskDtail?.id.toString() ?? '');
      return true;
      // logger.d(res);
    } catch (e) {
      return false;
    }
  }

  void shartToPlatform() {
    // shareToInstagram(type: Type.image);
  }

  // 获取系统粘贴的内容
  void getCopyValue() async {
    final clipboardData = await Clipboard.getData('text/plain');
    inputController.text = clipboardData?.text ?? '';
    _taskDetailModel.contentUrl = clipboardData?.text ?? '';
    notifyListeners();
  }

  // 刷新详情信息
  void refreshTaskDetail(int id, String taskType) {
    // 刷新详情数据 发布-> 返回详情
    setTaskType(taskType);
    initTaskDetail(id.toString());
  }

  // 修改获取任务标签的方法，处理数据类型转换
  List<Map<String, dynamic>>? get taskTagsRaw {
    if (_taskDetailModel.taskDtail?.taskConfigModel?.taskTagBoList != null) {
      return (_taskDetailModel.taskDtail!.taskConfigModel!.taskTagBoList
              as List)
          .map((item) => item as Map<String, dynamic>)
          .toList();
    }
    return null;
  }

  // 获取任务标签名称列表
  List<String> get taskTagNames {
    if (taskTagsRaw != null) {
      return taskTagsRaw!
          .map((tag) => tag['name'] as String? ?? '')
          .where((name) => name.isNotEmpty)
          .toList();
    }
    return [];
  }
}
